package org.example.JVM.ClassLoader;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: farprt
 * @create: 2022-11-16 16:27
 **/
public class ByteCodeClassLoader extends ClassLoader {

    // 类名->字节码持有者
    private final Map<String, ByteCodeHolder> classes = new HashMap<>();

    public ByteCodeClassLoader(final ClassLoader parentClassLoader){
        super(parentClassLoader);
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        ByteCodeHolder holder = classes.get(name);
        if(holder !=null){
            byte[] bytes = holder.getByteCode();
            classes.remove(name);
            return defineClass(name,bytes,0,bytes.length);
        }
        return super.findClass(name);
    }

    public void add(final String name,final ByteCodeHolder holder){
        classes.put(name, holder);
    }
}